﻿using NewRen.Models.ViewModel;
using NewRen.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using NewRen.Schemas;
using NewRen.Models.DataModel;
using NewRen.Helpers;
using Newtonsoft.Json;
using NewRen.Log4net;

namespace NewRen.Controllers
{
   
    public class UserController : BaseController
    {
        public static string apikey = "ad5021f3041c73c40c791f1bf24614c2";
        public static long tpl_id = 903571;

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [Route("Login")]
        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            try
            {
                if (User.Identity.IsAuthenticated == true && (Session["usertype"] != null))
                {
                    return Redirect("/");
                }
                ViewBag.returnUrl = returnUrl;
                return View();
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("登录页面加载出错", HttpHelper.GetIPAddress()), ex);
                return Redirect("/");
            }
        }


        [Route("Login")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(vLogin model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (model.UserType == UserType.User)
                    {
                        User user = new User();
                        model.Password = Helpers.Encryt.GetMD5(model.Password);
                        user = db.Users.Where(u => u.UserName == model.Username && u.Password == model.Password).SingleOrDefault();
                        if (user == null)
                        {
                            ModelState.AddModelError("", "用户名或密码错误！");
                        }
                        else
                        {
                            Session["usertype"] = UserType.User;
                            FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);

                            IntegrationRecord integrationrecord = new IntegrationRecord();
                            integrationrecord = (from i in db.IntegrationRecords where i.UserID == user.ID orderby i.Time descending select i).FirstOrDefault();

                            if (integrationrecord != null)
                            {
                                if (string.Format("{0:D}", integrationrecord.Time) != string.Format("{0:D}", DateTime.Now))
                                {
                                    integrationrecord.Integration = 10;
                                    integrationrecord.Time = DateTime.Now;
                                    integrationrecord.Hint = "每日首次登陆获取积分";
                                    db.IntegrationRecords.Add(integrationrecord);
                                    user.Integration = user.Integration + 10;
                                    db.SaveChanges();
                                }
                            }
                            else
                            {
                                IntegrationRecord integrationrecord1 = new IntegrationRecord();
                                integrationrecord1.UserID = user.ID;
                                integrationrecord1.Integration = 10;
                                integrationrecord1.Time = DateTime.Now;
                                integrationrecord1.Hint = "每日首次登陆获取积分";
                                db.IntegrationRecords.Add(integrationrecord1);
                                user.Integration = user.Integration + 10;
                                db.SaveChanges();
                            }
                            log.Info(new LogContent(user.UserName + "-用户登录", Helpers.HttpHelper.GetIPAddress()));

                            if (string.IsNullOrEmpty(returnUrl))
                                return RedirectToAction("Index", "Home");
                            else
                                return Redirect(returnUrl);
                        }
                    }
                    else if (model.UserType == UserType.UserGroup)
                    {
                        UserGroup user = new UserGroup();
                        model.Password = Helpers.Encryt.GetMD5(model.Password);
                        user = db.UserGroups.Where(ug => ug.LoginName == model.Username && ug.LoginPassword == model.Password).SingleOrDefault();
                        if (user == null)
                        {
                            ModelState.AddModelError("", "用户名或密码错误！");
                        }
                        else
                        {
                            Session["usertype"] = UserType.UserGroup;
                            FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                            if (string.IsNullOrEmpty(returnUrl))
                                return RedirectToAction("Index", "Home");
                            else
                                return Redirect(returnUrl);
                        }
                    }
                    else if (model.UserType == UserType.Business)
                    {
                        Business user = new Business();
                        model.Password = Helpers.Encryt.GetMD5(model.Password);
                        user = db.Businesses.Where(b => b.LoginName == model.Username && b.LoginPassword == model.Password).SingleOrDefault();
                        if (user == null)
                        {
                            ModelState.AddModelError("", "用户名或密码错误！");
                        }
                        else
                        {
                            Session["usertype"] = UserType.Business;
                            FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                            if (string.IsNullOrEmpty(returnUrl))
                                return RedirectToAction("Index", "Home");
                            else
                                return Redirect(returnUrl);
                        }
                    }
                    else
                    {
                        return RedirectToAction("/Shared/AccessDenied");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "登陆信息错误请重新填写！");
                }
                ViewBag.returnUrl = returnUrl;
                return View(model);
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("登录出错", HttpHelper.GetIPAddress()), ex);
                ViewBag.returnUrl = returnUrl;
                return View();
            }
        }
        #endregion

        #region 注册
        [Route("Register")]
        public ActionResult Register()
        {
            return View();
        }
        #endregion

        #region 注册
        [Route("RegisterDetail")]
        public ActionResult RegisterDetail(int id)
        {
            return View();
        }
        #endregion

        #region 个人信息展示
        /// <summary>
        /// 个人信息展示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowUser]
        public ActionResult Show(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user != null)
            {
                ViewBag.user = new vUser(user);
                if (user.UserGroupID != null)
                {
                    UserGroup usergroup = new UserGroup();
                    usergroup = (from u in db.UserGroups where user.UserGroupID == u.ID select u).SingleOrDefault();
                    ViewBag.UserGroup = usergroup;
                }
                return View();
            }
            else
            {
                log.Error(new LogContent("个人信息展示页面加载出错", HttpHelper.GetIPAddress()), null);
                return Redirect("/User/Show/" + id);
            }
        }
        #endregion

        #region 积分明细显示
        /// <summary>
        /// 积分显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowUser]
        public ActionResult IntegrationShow(int id, int p = 0)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.user = new vUser(user);
                    IEnumerable<IntegrationRecord> query = db.IntegrationRecords.AsEnumerable();
                    query = query.Where(i => i.UserID == id);
                    query = query.OrderByDescending(t => t.Time);
                    ViewBag.PageInfo = PagerHelper.Do(ref query, 10, p);
                    return View(query);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("积分明细显示页面加载出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/IntegrationShow/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region   金钱明细显示
        /// <summary>
        /// 金钱明细显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowUser]
        public ActionResult MoneyShow(int id, int p = 0)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.user = new vUser(user);
                    IEnumerable<MoneyRecord> query = db.MoneyRecords.AsEnumerable();
                    query = query.Where(m => m.UserID == id);
                    query = query.OrderByDescending(t => t.Time);
                    ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
                    return View(query);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("金钱明细显示页面加载出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/IntegrationShow/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 个人概述显示
        [Schemas.AccessShowUser]
        public ActionResult DescriptionShow(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.user = new vUser(user);
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("金钱明细显示页面加载出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/DescriptionShow/" + id);
                }

            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }

        #endregion

        #region 浏览记录更多
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowUser]
        public ActionResult Browserecord(int id, int p = 0)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.user = new vUser(user);
                    IEnumerable<BrowseRecord> query = db.BrowseRecords.AsEnumerable();
                    query = query.Where(b => b.UserID == id);
                    query = query.OrderByDescending(t => t.Time);
                    ViewBag.PageInfo = PagerHelper.Do(ref query, 10, p);
                    return View(query);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("浏览记录更多页面加载出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/DescriptionShow/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 修改用户信息界面
        /// <summary>
        /// 修改用户信息界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Schemas.AccessShowUser]
        public ActionResult Edit(int id)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.user = user;
                    List<SelectListItem> ListSex = new List<SelectListItem>();
                    ListSex.Add(new SelectListItem { Text = "女", Value = "0", Selected = (user.SexAsInt == 0 ? true : false) });
                    ListSex.Add(new SelectListItem { Text = "男", Value = "1", Selected = (user.SexAsInt == 1 ? true : false) });
                    ViewBag.Sex = ListSex;
                    ViewBag.Jobs = db.Jobs.ToList();
                    ViewBag.Cities = db.Cities.ToList();
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改用户信息界面加载出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/DescriptionShow/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 修改个人信息
        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowUser]
        public ActionResult Edit(vEdit model, int? cityID, int? districtID, int? townID)
        {
            User user = db.Users.Find(model.ID);
            if (user != null)
            {
                try
                {
                    ViewBag.user = user;
                    if (ModelState.IsValid)
                    {
                        if (cityID.HasValue)
                        {
                            var city = db.Cities.Find(cityID);
                            user.City = city.CityName;
                        }
                        if (districtID.HasValue)
                        {
                            var district = db.Districts.Find(districtID);
                            user.District = district.DistrictName;
                        }
                        if (townID.HasValue)
                        {
                            var town = db.Towns.Find(townID);
                            user.Town = town.TownName;
                        }
                        user.SexAsInt = model.SexAsInt;
                        user.Phone = model.Phone;
                        user.Address = model.Address;
                        user.Birthday = model.Birthday;
                        user.Email = model.Email;
                        user.RealName = model.RealName;
                        user.QQ = model.QQ;
                        user.WhatApp = model.WhatApp;
                        user.Job = model.Job;
                        user.Description = model.Description;
                        user.UserGroupID = model.UserGroupID;
                        db.SaveChanges();
                        //FormsAuthentication.SetAuthCookie(model.UserName, false);
                        return RedirectToAction("Show/" + user.ID);
                    }
                    else
                    {
                        ModelState.AddModelError("", "修改的信息输入错误!");
                    }
                    List<SelectListItem> ListSex = new List<SelectListItem>();
                    ListSex.Add(new SelectListItem { Text = "女", Value = "0", Selected = (user.SexAsInt == 0 ? true : false) });
                    ListSex.Add(new SelectListItem { Text = "男", Value = "1", Selected = (user.SexAsInt == 1 ? true : false) });
                    ViewBag.Sex = ListSex;
                    ViewBag.Jobs = db.Jobs.ToList();
                    ViewBag.Cities = db.Cities.ToList();
                    ViewBag.user = user;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改个人信息出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/DescriptionShow/" + model.ID);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion


        #region 修改个人密码界面
        /// <summary>
        /// 修改个人密码界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Schemas.AccessShowUser]
        public ActionResult PwdEdit(int id)
        {
            try
            {
                User user = db.Users.Find(id);
                if (user != null)
                {

                    ViewBag.user = new vPwdEdit(user);
                    return View();
                }
                else
                {
                    return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("修改个人密码界面加载出错", HttpHelper.GetIPAddress()), ex);
                return Redirect("/Shared/info?msg=出现错误");
            }
        }
        #endregion

        #region 修改个人密码信息
        /// <summary>
        /// 修改个人密码信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Schemas.AccessShowUser]
        [ValidateAntiForgeryToken]
        public ActionResult PwdEdit(vPwdEdit model)
        {
            User user = db.Users.Find(model.ID);
            if (user != null)
            {
                try
                {
                    if (ModelState.IsValid)
                    {

                        if (!string.IsNullOrEmpty(model.Password))
                        {
                            if (!user.Password.Equals(Helpers.Encryt.GetMD5(model.Password)))
                            {
                                return Redirect("/Shared/Info?msg=" + "您输入原始密码错误！");
                            }
                            else
                            {
                                user.Password = Helpers.Encryt.GetMD5(model.PasswordNew);
                                db.SaveChanges();
                                return RedirectToAction("Show/" + model.ID);
                            }
                        }
                        else
                        {
                            return RedirectToAction("Show/" + model.ID);
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "修改的信息输入错误!");
                    }
                    ViewBag.user = new vPwdEdit(user);
                    return View(model);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改个人密码信息出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/DescriptionShow/" + model.ID);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 修改图像
        /// <summary>
        /// 修改图像
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowUser]
        public ActionResult PictureEdit(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.User = user;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改图像页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/DescriptionShow/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 修改头像
        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowUser]
        public ActionResult PictureEdit(vEdit model, HttpPostedFileBase file)
        {
            User user = db.Users.Find(model.ID);
            if (user != null)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        user.Picture = model.Picture;
                        if (file != null)
                        {
                            System.IO.Stream stream = file.InputStream;
                            //byte[] buffer = new byte[stream.Length];
                            //stream.Read(buffer, 0, (int)stream.Length);
                            //stream.Close();
                            byte[] buffer = Image.CompressionImage(stream, 10);
                            user.Picture = buffer;
                        }
                        db.SaveChanges();
                        return RedirectToAction("Show/" + model.ID);
                    }
                    else
                    {
                        ModelState.AddModelError("", "修改的信息输入错误!");
                    }
                    ViewBag.user = user;
                    return View(model);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改图像页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/PictureEdit/" + model.ID);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 显示图像

        /// <summary>
        /// 显示图像
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowPicture(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user != null)
            {
                return File(user.Picture, "image/jpg");
            }
            else
            {
                return File("/Images/userphoto.png", "image/jpg");
            }
        }
        #endregion


        #region 注销
        /// <summary>
        ///  注销 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ValidateSID]
        public ActionResult Logout(string returnUrl)
        {
            FormsAuthentication.SignOut();
            Session["usertype"] = null;
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return Redirect(returnUrl);
            }
        }
        #endregion


        #region 生成验证码
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ValidateCode()
        {
            Helpers.ValidateCode validateCode = new Helpers.ValidateCode();
            string code = validateCode.CreateValidateCode(4);
            Session["validateCode"] = code;
            byte[] buffer = validateCode.CreateValidateGraphic(code);
            return File(buffer, "image/jpeg");
        }

        #endregion

        #region 发送手机验证码
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult SendCode(string code, string phone)
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                string validateCode = Session["validateCode"] == null ? string.Empty : Session["validateCode"].ToString();
                if (string.IsNullOrEmpty(validateCode))
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "验证码错误";
                    return Json(ajaxModel);
                }
                if (validateCode != code)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "验证码错误";
                    return Json(ajaxModel);
                }
                if (string.IsNullOrEmpty(phone))
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "电话号不能为空";
                    return Json(ajaxModel);
                }


                Models.User user = new Models.User();
                user = db.Users.Where(u => u.Phone == phone).FirstOrDefault();

                if (user != null)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "该手机号已经注册过了";
                    return Json(ajaxModel);
                }


                string pcode = Helpers.String.RandomCode().ToString();
                string tpl_value = "#code#=" + Uri.EscapeDataString(pcode);
                string result = SendMessage.tplSendSms(apikey, tpl_id, tpl_value, phone);

                MessageBack back = JsonConvert.DeserializeObject<MessageBack>(result);

                ajaxModel.Statu = back.code.ToString();
                ajaxModel.Msg = back.msg;

                if (back.msg == "OK" || back.msg == "ok")
                {
                    var _validateCode = db.ValidateCodes.Where(vc => vc.Phone == phone).FirstOrDefault();
                    if (_validateCode == null)
                    {
                        _validateCode = new Models.ValidateCode();
                        _validateCode.Time = DateTime.Now;
                        _validateCode.Code = pcode;
                        _validateCode.Phone = phone;
                        db.ValidateCodes.Add(_validateCode);
                    }
                    else
                    {
                        _validateCode.Time = DateTime.Now;
                        _validateCode.Code = pcode;
                        _validateCode.Phone = phone;
                    }
                    db.SaveChanges();
                    ajaxModel.Statu = back.msg;
                    ajaxModel.Msg = "获取成功！";
                }
                else
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "获取失败！";
                }
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败！";
                log.Error(new LogContent("发送手机验证码出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel);
        }
        #endregion

        #region 电话注册
        /// <summary>
        /// 电话注册
        /// </summary>
        /// <param name="code"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        public ActionResult PhoneRegister(string code, string phone)
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                var user = db.Users.Where(u => u.Phone == phone).FirstOrDefault();
                if (user != null)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "该手机号存在！";
                    return Json(ajaxModel);
                }
                else
                {
                    var _validateCode = db.ValidateCodes.Where(vc => vc.Phone == phone).FirstOrDefault();
                    if (_validateCode == null)
                    {
                        ajaxModel.Statu = "err";
                        ajaxModel.Msg = "验证码出错，请重新验证！";
                    }
                    else
                    {
                        if ((DateTime.Now - _validateCode.Time).Minutes <= 1)
                        {
                            if (_validateCode.Code.Equals(code))
                            {
                                user = new Models.User();
                                user.Phone = phone;
                                user.AddTime = DateTime.Now;
                                db.Users.Add(user);
                                db.SaveChanges();
                                ajaxModel.Statu = "ok";
                                ajaxModel.Msg = "注册成功！";
                                ajaxModel.BackUrl = "/User/RegisterComplete/" + user.ID;

                            }
                            else
                            {
                                ajaxModel.Statu = "err";
                                ajaxModel.Msg = "验证码输入错误！";
                            }
                        }
                        else
                        {
                            ajaxModel.Statu = "err";
                            ajaxModel.Msg = "验证码失效";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败！";
                log.Error(new LogContent("电话注册出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel);
        }

        #endregion

        #region 注册信息完善
        /// <summary>
        ///  注册信息完善
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessCompleteRegister]
        public ActionResult RegisterComplete(int id)
        {
            var user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.User = user;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("注册信息完善页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/RegisterComplete/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }

        /// <summary>
        /// 注册信息完善
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessCompleteRegister]
        public ActionResult RegisterComplete(int id, vRegisterComplete model)
        {
            var _user = db.Users.Find(id);
            if (_user != null)
            {
                try
                {
                    ViewBag.User = _user;
                    if (ModelState.IsValid)
                    {
                        var user = new Models.User();
                        user = db.Users.Where(u => u.UserName == model.Username).FirstOrDefault();
                        if (user == null)
                        {
                            user = new Models.User();
                            user = db.Users.Find(id);
                            if (user != null)
                            {
                                user.UserName = model.Username;
                                user.Password = Helpers.Encryt.GetMD5(model.Password);
                                db.SaveChanges();
                                return Redirect("/Login");
                            }
                            else
                            {
                                ModelState.AddModelError("", "该用户名不存在！请重新用手机号注册");
                            }

                        }
                        else
                        {
                            ModelState.AddModelError("", "该用户名已经存在！");
                        }

                    }
                    else
                    {
                        ModelState.AddModelError("", "注册信息填写错误请重新填写！");
                    }
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("注册信息完善页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/RegisterComplete/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 牛人展示
        /// <summary>
        /// 牛人展示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PersonalShow(int id, int p = 0)
        {
            try
            {
                User user = new User();
                user = db.Users.Find(id);
                if (user != null)
                {
                    user.PV = user.PV + 1;
                    user.TodayPV = user.TodayPV + 1;
                    db.SaveChanges();
                    ViewBag.user = new vUser(user);
                    var u = "";
                    if (user.RealName == null)
                    {
                        u = user.UserName;
                    }
                    else
                    {
                        u = user.RealName;
                    }
                    if (CurrentUser != null)
                    {
                        BrowseRecord browserecord = new BrowseRecord();
                        string url = Request.Url.ToString();
                        browserecord = db.BrowseRecords.Where(br => br.URL == url && br.UserID == CurrentUser.ID).FirstOrDefault();
                        if (browserecord == null)
                        {
                            BrowseRecord addbrowserecord = new BrowseRecord();
                            addbrowserecord.UserID = CurrentUser.ID;
                            addbrowserecord.URL = url;
                            addbrowserecord.Title = "牛人展示——" + u;
                            addbrowserecord.Time = DateTime.Now;

                            db.BrowseRecords.Add(addbrowserecord);
                            db.SaveChanges();
                        }
                        else
                        {
                            db.BrowseRecords.Remove(browserecord);
                            BrowseRecord updatebrowserecord = new BrowseRecord();
                            updatebrowserecord.UserID = CurrentUser.ID;
                            updatebrowserecord.URL = url;
                            updatebrowserecord.Title = "牛人展示——" + u;
                            updatebrowserecord.Time = DateTime.Now;

                            db.BrowseRecords.Add(updatebrowserecord);
                            db.SaveChanges();

                        }
                        var collect = db.Collects.Where(c => c.CollectTypeAsInt == 0 && c.TID == id && c.UserID == CurrentUser.ID).FirstOrDefault();
                        if (collect == null)
                        {
                            ViewBag.IsCollected = false;
                        }
                        else
                        {
                            ViewBag.IsCollected = true;
                        }
                    }
                    else
                    {
                        ViewBag.IsCollected = false;
                    }
                    IEnumerable<MessageBoard> query = db.MessageBoards.Where(m => m.ToUserID == user.ID).OrderByDescending(m => m.Time).AsEnumerable();
                    ViewBag.PageInfo = PagerHelper.Do(ref query, 5, p);
                    List<vMessageBoard> MessageBoards = new List<vMessageBoard>();
                    foreach (var item in query)
                    {
                        MessageBoards.Add(new vMessageBoard(item));
                    }
                    return View(MessageBoards);
                }
                else
                {
                    return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("注册信息完善页面出错", HttpHelper.GetIPAddress()), ex);
                return Redirect("/User/PersonalShow/" + id);
            }

        }

        #endregion

        #region  浏览记录删除
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Deletebrowserecord()
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                List<BrowseRecord> delbrowserecord = new List<BrowseRecord>();
                delbrowserecord = (from d in db.BrowseRecords where d.UserID == CurrentUser.ID select d).ToList();
                foreach (BrowseRecord bro in delbrowserecord)
                {
                    db.BrowseRecords.Remove(bro);
                    db.SaveChanges();
                }
                ajaxModel.Statu = "ok";
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("浏览记录删除出错", HttpHelper.GetIPAddress()), ex);
                ajaxModel.Statu = "err";
            }
            return Json(ajaxModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region   牛人评论
        /// <summary>
        /// 牛人评论
        /// </summary>
        /// <param name="content"></param>
        /// <param name="rid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MessageAdd(string content, int rid, int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                User fromname = (from r in db.Users where r.ID == rid select r).SingleOrDefault();
                User toname = (from r in db.Users where r.ID == id select r).SingleOrDefault();
                MessageBoard messageboard = new MessageBoard { Description = content, FromUserID = rid, ToUserID = id };
                messageboard.Time = DateTime.Now;
                messageboard.FromUser = fromname;
                messageboard.ToUser = toname;
                db.MessageBoards.Add(messageboard);
                db.SaveChanges();
                ajaxModel.Data = new vMessageBoard(messageboard);
                ajaxModel.Statu = "ok";
                ajaxModel.Msg = "获取成功";
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败";
                log.Error(new LogContent("牛人评论出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 赞
        /// <summary>
        /// 赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateSID]
        public ActionResult Up(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            var user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    user.Ups = user.Ups + 1;
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "赞成功！";
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "赞失败！";
                    log.Error(new LogContent("牛人赞出错", HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "赞失败！";
            }
            return Json(ajaxModel);
        }
        #endregion


        #region 踩
        /// <summary>
        /// 赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateSID]
        public ActionResult Down(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            var user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    user.Downs = user.Downs + 1;
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "踩成功！";
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "踩失败！";
                    log.Error(new LogContent("牛人踩出错", HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "踩失败！";
            }
            return Json(ajaxModel);
        }
        #endregion


        #region 增加收藏
        /// <summary>
        /// 增加收藏
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult AddCollect(int id)
        {
            AjaxModel model = new AjaxModel();
            Collect collect = new Collect();
            try
            {
                collect = db.Collects.Where(u => u.TID == id && u.UserID == CurrentUser.ID && u.CollectTypeAsInt == 0).FirstOrDefault();
                if (collect == null)
                {
                    collect = new Collect();
                    collect.CollectType = CollectType.User;
                    collect.UserID = CurrentUser.ID;
                    collect.TID = id;
                    collect.Time = DateTime.Now;
                    collect.CollectTypeAsInt = 0;
                    db.Collects.Add(collect);
                    db.SaveChanges();
                    model.Statu = "ok";
                }
                else
                {
                    model.Statu = "err";
                    model.Msg = "该牛人已收藏！";
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("牛人收藏出错", HttpHelper.GetIPAddress()), ex);
                model.Statu = "err";
                model.Msg = "收藏失败！";
            }
            return Json(model);
        }

        #endregion

        #region
        /// <summary>
        /// 取消收藏
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult CancelCollect(int id)
        {
            AjaxModel model = new AjaxModel();
            Collect collect = new Collect();

            try
            {
                collect = db.Collects.Where(u => u.TID == id && u.UserID == CurrentUser.ID && u.CollectTypeAsInt == 0).FirstOrDefault();
                if (collect != null)
                {
                    db.Collects.Remove(collect);
                    db.SaveChanges();
                    model.Statu = "ok";
                }
                else
                {
                    model.Statu = "err";
                    model.Msg = "未收藏！";
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("牛人取消收藏出错", HttpHelper.GetIPAddress()), ex);
                model.Statu = "err";
                model.Msg = "取消收藏失败！";
            }
            return Json(model);
        }
        #endregion
        #region 收藏管理
        /// <summary>
        /// 收藏管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CollectManager(int id, int collecttype = 0, int p = 0)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.user = new vUser(user);
                    IEnumerable<Collect> query = db.Collects.Where(u => u.UserID == id && u.CollectTypeAsInt == collecttype);
                    List<vCollect> collects = new List<vCollect>();
                    ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
                    foreach (var item in query)
                    {
                        collects.Add(new vCollect(item));
                    }
                    return View(collects);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("牛人收藏管理出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/CollectManager/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }


        /// <summary>
        ///  删除收藏
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RemoveCollect(int id)
        {
            Collect collect = new Collect();
            try
            {
                collect = db.Collects.Find(id);
                if (collect != null)
                {
                    db.Collects.Remove(collect);
                    db.SaveChanges();
                    return Content("ok");
                }
                else
                {
                    return Content("err");
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("牛人删除收藏出错", HttpHelper.GetIPAddress()), ex);
                return Content("err");
            }

        }
        #endregion

        #region 充值
        public ActionResult PayMoney(int id)
        {
            User user = db.Users.Find(id);
            if (user != null)
            {
                ViewBag.User = new vUser(user);
                return View();
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
        #endregion

        [HttpGet]
        public ActionResult Forgetpassword()
        {
            return View();
        }

        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult SendForgetCode(string phone)
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                if (string.IsNullOrEmpty(phone))
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "电话号不能为空";
                    return Json(ajaxModel);
                }

                var user = db.Users.Where(u => u.Phone == phone).FirstOrDefault();
                if (user == null)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "不存在该用户";
                    return Json(ajaxModel);
                }
                else
                {
                    string pcode = Helpers.String.RandomCode().ToString();
                    string tpl_value = "#code#=" + Uri.EscapeDataString(pcode);
                    string result = SendMessage.tplSendSms(apikey, tpl_id, tpl_value, phone);

                    MessageBack back = JsonConvert.DeserializeObject<MessageBack>(result);

                    ajaxModel.Statu = back.code.ToString();
                    ajaxModel.Msg = back.msg;

                    if (back.msg == "OK" || back.msg == "ok")
                    {
                        var _validateCode = db.ValidateCodes.Where(vc => vc.Phone == phone).FirstOrDefault();
                        if (_validateCode == null)
                        {
                            _validateCode = new Models.ValidateCode();
                            _validateCode.Time = DateTime.Now;
                            _validateCode.Code = pcode;
                            _validateCode.Phone = phone;
                            db.ValidateCodes.Add(_validateCode);
                        }
                        else
                        {
                            _validateCode.Time = DateTime.Now;
                            _validateCode.Code = pcode;
                            _validateCode.Phone = phone;
                        }
                        db.SaveChanges();
                        ajaxModel.Statu = back.msg;
                        ajaxModel.Msg = "获取成功！";
                    }
                    else
                    {
                        ajaxModel.Statu = "err";
                        ajaxModel.Msg = "获取失败！";
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("发送手机验证码出错", HttpHelper.GetIPAddress()), ex);
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败！";
            }
            return Json(ajaxModel);
        }

        [HttpPost]
        [ValidateSID]
        public ActionResult PhoneFindPassword(string code, string phone)
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                var user = db.Users.Where(u => u.Phone == phone).FirstOrDefault();
                if (user == null)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "该手机号不存在！";
                    return Json(ajaxModel);
                }
                else
                {
                    var _validateCode = db.ValidateCodes.Where(vc => vc.Phone == phone).FirstOrDefault();
                    if (_validateCode == null)
                    {
                        ajaxModel.Statu = "err";
                        ajaxModel.Msg = "验证码出错，请重新验证！";
                    }
                    else
                    {
                        if ((DateTime.Now - _validateCode.Time).Minutes <= 1)
                        {
                            if (_validateCode.Code.Equals(code))
                            {
                                ajaxModel.Statu = "ok";
                                ajaxModel.Msg = "验证成功！";
                                ajaxModel.BackUrl = "/User/ForgetpasswordComplete/" + user.ID;
                            }
                            else
                            {
                                ajaxModel.Statu = "err";
                                ajaxModel.Msg = "验证码输入错误！";
                            }
                        }
                        else
                        {
                            ajaxModel.Statu = "err";
                            ajaxModel.Msg = "验证码失效";

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("手机验证出错", HttpHelper.GetIPAddress()), ex);
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "验证码失效";
            }
            return Json(ajaxModel);
        }

        /// <summary>
        /// 忘记密码处理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ForgetpasswordComplete(int id)
        {
            var user = db.Users.Find(id);
            if (user != null)
            {
                ViewBag.User = user;
                return View();
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ForgetpasswordComplete(string Password, string Confirm, int id)
        {
            var user = db.Users.Find(id);
            if (user != null)
            {
                try
                {
                    ViewBag.User = user;
                    if (ModelState.IsValid)
                    {
                        if (string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Confirm))
                        {
                            ModelState.AddModelError("", "密码或者密码重复不能为空！");
                        }
                        else
                        {
                            if (Password != Confirm)
                            {
                                ModelState.AddModelError("", "两次输入密码不一致！");
                            }
                            else
                            {
                                user.Password = Helpers.Encryt.GetMD5(Password);
                                db.SaveChanges();
                                return Redirect("/Login");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "找回密码信息填写错误，请重新填写！");
                    }
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("找回密码信息出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/User/ForgetpasswordComplete/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/info?msg=该用户不存在，请不要不合理操作");
            }
        }
    }
}